package com.shopping.auth.controller;

import com.alibaba.fastjson.JSON;
import com.shopping.auth.component.WeiboAuthArgs;
import com.shopping.auth.feign.MemberFeignService;
import com.shopping.auth.vo.SocialUserVo;
import com.shopping.common.constant.AuthServerConstant;
import com.shopping.common.utils.HttpUtils;
import com.shopping.common.utils.R;
import com.shopping.common.vo.MemberRespVo;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuthController {


    @Resource
    MemberFeignService memberFeignService;

    @Resource
    WeiboAuthArgs weiboAuthArgs;


    @GetMapping("/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) {
        Map<String, String> map = weiboAuthArgs.bodies(code);
        System.out.println("map = " + map);
        try {
            HttpResponse post = HttpUtils.doPost("https://api.weibo.com",
                    "/oauth2/access_token",
                    "post",
                    new HashMap<>(),
                    new HashMap<>(),
                    map);
            if (post.getStatusLine().getStatusCode() != 200) {
                return "redirect:http://auth.shopping.com/login.html";
            }
            String json = EntityUtils.toString(post.getEntity());
            SocialUserVo socialUserVo = JSON.parseObject(json, SocialUserVo.class);
            //获得信息后,判断是否是第一次登陆
            R r = memberFeignService.oauthLogin(socialUserVo);
            if (r.getCode() != 0) {
                return "redirect:http://auth.shopping.com/login.html";
            }
            String memberEntityJson = (String) r.get("msg");
            MemberRespVo memberRespVo = JSON.parseObject(memberEntityJson, MemberRespVo.class);
            System.out.println("memberRespVo = " + memberRespVo);
            session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "redirect:http://www.shopping.com";
    }
}
